<template>
  <div class="preview-container" style="width: 100vw;">
    <!-- 左侧表单区域 -->
    <el-container class="form-area" style="width: 500px; min-width: 400px;">
      <el-header style="overflow: hidden;">
        <div class="segmentedWrapper" style="display: flex; transition: transform 0.3s ease;">
          <!-- 不能使用v-model绑定，因为未更新的activeForm在缓存的时候有用 -->
          <el-segmented
            class="segmented-container"
            :options="formOptions"
            size="large"
            style="margin: 16px 0; width: max-content;"
            :model-value="activeForm"
            @change="handleSegmentedChange"
          />
        </div>
      </el-header>
      <el-main style="overflow-y: auto; height: calc(100vh - 170px);">
        <component 
          :is="currentForm"
          ref="currentFormRef"
          :key="activeForm"
          v-if="formDataCache[activeForm]"
          :initialData="formDataCache[activeForm]"
        />
      </el-main>
    </el-container>

    <!-- 右侧预览区域 -->
    <div class="preview-area">
      <div class="resume-content" :style="{width: resumeWidth}">
        <div class="father" style="width: 100%;">
          <component 
            :is="resumeType"
            ref="resumeRef"
            v-if="formDataCache[activeForm]"
            :colorTemplate = "themeColor"
            :initialData="formDataCache"
          />
        </div>
      </div>

      <div class="control-panel">

        <!-- 样式调整 -->
        <div class="style-controls">
          <el-button-group>
            <el-button 
              v-for="size in ['小', '中', '大']" 
              :key="size"
              @click="changeFontSize(size)"
            >{{ size }}</el-button>
          </el-button-group>

          <el-slider 
            v-model="zoomLevel"
            :min="0"
            :max="100"
            :step="5"
            show-stops
            style="width: 200px; margin: 0 16px;"
          />

          <el-button-group class="theme-buttons">
            <el-button
              v-for="scheme in colorSchemes"
              :key="scheme.name"
              :style="{ backgroundColor: scheme.colors[0] }"
              @click="changeTheme(scheme.colors)"
            >{{ scheme.name }}</el-button>
          </el-button-group>
        </div>

        <!-- 操作按钮 -->
        <div class="action-buttons">
          <el-button @click="saveDraft">保存草稿</el-button>
          <el-button type="primary" @click="exportPDF">导出PDF</el-button>
          <el-button @click="quit">退出</el-button>
        </div>

      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, nextTick, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { useRoute } from 'vue-router'
import html2canvas from 'html2canvas'
import jsPDF from 'jspdf'
import { useResumeStore } from '../store/resume'
import EducationForm from './Forms/EducationForm.vue'
import WorkExperienceForm from './Forms/WorkExperienceForm.vue'
import JobObjectiveForm from './Forms/JobObjectiveForm.vue'
import ProjectExperienceForm from './Forms/ProjectExperienceForm.vue'
import SkillsForm from './Forms/SkillsForm.vue'
import BasicInfoForm from './Forms/BasicInfoForm.vue'
import AwardsForm from './Forms/AwardsForm.vue'
import CampusExperienceForm from "./Forms/CampusExperienceForm.vue"

const resumeStore = useResumeStore()
const router = useRouter()
const resumeRef = ref(null)
const resumeType = ref()
const route = useRoute()
// 缩放级别
const zoomLevel = ref(100)
// 字体大小
const fontSize = ref('中')

const resumeWidth = computed(() => {
  return `${30 + (zoomLevel.value * 0.6)}%`;
});
const fontSizeMap = {
  '小': '14px',
  '中': '16px', 
  '大': '18px'
}

// 配色方案
const colorSchemes = ref([
  {
    name: '渐变蓝',
    colors: ['#1890ff', '#4da6ff', '#80bdff', '#b3d4ff', '#e6f0ff', '#ffffff']
  },
  {
    name: '渐变',
    colors: ['#71ae46', '#96b744', '#c4cc38', '#ebe12a', '#eab026', '#e3852b', '#d85d2a', '#ce2626', '#ac2026', '#71ae46', '#96b744', '#c4cc38']
  },
])
const themeColor = ref(colorSchemes.value[0].colors)

const formDataCache = ref({})
const formOptions = [
  { label: '基本信息', value: 'basic' },
  { label: '教育背景', value: 'education' },
  { label: '工作经历', value: 'workExperience' },
  { label: '项目经验', value: 'projects' },
  { label: '获奖状况', value: 'awards' },
  { label: '校园经历', value: 'campusExperience' },
  { label: '求职意向', value: 'jobObjectives' },
  { label: '技能特长', value: 'skills' }
]

const formComponents = {
  basic: BasicInfoForm,
  education: EducationForm,
  workExperience: WorkExperienceForm,
  projects: ProjectExperienceForm,
  awards: AwardsForm,
  campusExperience: CampusExperienceForm,
  jobObjectives: JobObjectiveForm,
  skills: SkillsForm,
}

// 表单相关逻辑
const activeForm = ref('basic')
const currentFormRef = ref(null)

const currentForm = computed(() => {
  return formComponents[activeForm.value]
})

onMounted(async () => {
  if (route.query.template && route.query.address) {
    try {
      const component = await import(/* @vite-ignore */ route.query.address)
      resumeType.value = component.default

      await resumeStore.loadProfile()
      if (resumeStore.profile) {
        formDataCache.value = resumeStore.profile
      }else{
        formDataCache.value = {
          basic:{},
          education:[],
          workExperience:[],
          projects:[],
          skills:[],
          campusExperience:[],
          jobObjectives:[],
          awards:[],
        }
      }
      console.log("从数据库获取原始数据：",formDataCache.value);
      
    } catch (error) {
      console.error('Failed to load template:', error)
    }
  }else if(route.query.id){
    const draft = resumeStore.drafts.find(d => d.id == route.query.id)
    if (draft) {
      try {
        const component = await import(/* @vite-ignore */ draft.address)
        resumeType.value = component.default
        
        formDataCache.value = draft.profile
        themeColor.value = draft.colorScheme
        fontSize.value = draft.fontSize

      } catch (error) {
        console.error('Failed to load template:', error)
      }
    }else{
      alert("该草稿不存在")
      router.push('/home')
    }
  }
})

const quit = ()=>{
  router.push('/home')
}

// 保存草稿
const saveDraft = async () => {
  const formData = await currentFormRef.value.getFormData()
  formDataCache.value[activeForm.value] = formData
  console.log("formDataCache:",formDataCache.value);
  const draftId = route.query.id
  const draft = {
    profile: formDataCache.value,
    colorScheme: themeColor.value,
    fontSize: fontSize.value,
    updatedAt: new Date().toISOString()
  }

  // 查找是否有旧草稿
  const oldDraft = draftId ? resumeStore.drafts.find(d => d.id === draftId) : null

  if (!oldDraft) {
    // 新草稿
    const timestamp = Date.now() & 0xFFF; // 取低12位（4096ms粒度）
    const random = Math.random() * 0x3FFF | 0; // 12位随机数
    const combined = ((timestamp << 12) | random) + 0x80000000; // 转为32位无符号整数
    
    draft.id = combined.toString(36).padStart(10, '0'); 
    draft.createdAt = new Date().toISOString()
    draft.address = route.query.address
    draft.template = route.query.template
    await resumeStore.saveDraft(draft)
  } else {
    // 更新草稿
    draft.id = oldDraft.id
    draft.createdAt = oldDraft.createdAt
    draft.address = oldDraft.address
    draft.template = oldDraft.template

    await resumeStore.deleteDraft(oldDraft.id)
    await resumeStore.saveDraft(draft)
  }

  ElMessage.success('草稿保存成功，你可以在草稿箱中查看')
  // router.push('/home')
}

// 导出PDF
const exportPDF = async () => {
  try {
    if (!resumeRef.value) {
      ElMessage.error('无法获取简历内容')
      return
    }
    // const canvas = await html2canvas(resumeRef.value.$el)
    // 使用高分辨率渲染 
    const scale = 3
    const canvas = await html2canvas(resumeRef.value.$el, { 
      scale,
      dpi: 192,
      // useCORS: true,
      // logging: false,
      // backgroundColor: '#FFFFFF',
      // ignoreElements: (element) => {
      //   // 忽略控制面板元素
      //   return element.classList?.contains('control-panel')
      // }
    })
    const imgData = canvas.toDataURL('image/jpg')
    const imgWidth = 210 // PDF宽度(mm)
    const imgHeight = (canvas.height * imgWidth) / canvas.width // 计算PDF高度
    
    // 创建自定义尺寸的PDF (宽度: imgWidth, 高度: imgHeight)
    const pdf = new jsPDF({
      orientation: 'portrait',
      unit: 'mm',
      format: [imgWidth, imgHeight]
    })

    // 添加完整图像到PDF (位置: 0,0; 尺寸: imgWidth x imgHeight)
    pdf.addImage(imgData, 'PNG', 0, 0, imgWidth, imgHeight)
    
    pdf.save('resume.pdf')
    ElMessage.success('PDF导出成功')
  } catch (error) {
    console.error('导出PDF失败:', error)
    ElMessage.error('PDF导出失败')
  }
}



const handleSegmentedChange = async (value) => {
  if (currentFormRef.value) {
    const formData = await currentFormRef.value.getFormData()
    formDataCache.value[activeForm.value] = formData
  }
  activeForm.value = value
  nextTick(() => {
    const segWidth = formOptions.length * 86;
    const showWidth = document.getElementsByClassName("segmentedWrapper")[0].offsetWidth
  
    //移动总距离 = seg总长度(seg长度*个数) - 展示长度
    const moveDistance = (segWidth - showWidth + 40) / formOptions.length
    const selectedIndex = formOptions.findIndex(option => option.value === value)

    const finalScroll = selectedIndex * moveDistance
    document.getElementsByClassName("segmentedWrapper")[0].style.transform = `translateX(-${finalScroll}px)`
  })
}
// 改变字体大小
const changeFontSize = (size) => {
  fontSize.value = size
}

// 改变主题色
const changeTheme = (colors) => {
  themeColor.value = colors; // 使用配色方案中的第一个颜色作为主色调
}

</script>

<style scoped>
.preview-container {
  display: flex;
  height: 100vh;
}

.form-area {
  min-width: 300px;
  padding: 20px;
  background-color: #f5f5f5;
  overflow-y: auto;
  transition: width 0.3s ease;
}

.form-header {
  background-color: white;
  padding: 16px;
  margin: -20px -20px 20px -20px;
  border-bottom: 1px solid #ebeef5;
  overflow: hidden;
}

.preview-area {
  width: calc(70% - 2%);
  display: flex;
  flex-direction: column;
  background-color: #fff;
  align-items: center;
}

.resume-content {
  flex: 1;
  padding: 0;
  overflow-y: auto;
  display: flex;
  justify-content: center;
  /* background-color: pink; */
  margin: 0;
  margin-top: 20px;
  container-type: inline-size;
}

.control-panel {
  width: 100%;
  padding: 16px;
  background-color: white;
  box-shadow: 0 -2px 12px rgba(0, 0, 0, 0.1);
  height: 120px;
  box-sizing: border-box;
}

.style-controls {
  display: flex;
  justify-content: space-between;
  margin-bottom: 16px;
}

.theme-buttons .el-button {
  width: 32px;
  height: 32px;
  padding: 0;
}

.action-buttons {
  text-align: center;
}
</style>
